package com.qm.aop;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.qm.vo.QmResult;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;

/**
 @author james
 @create 2021-03-12 14:09
 */
//spring中的通知 核心原理：Spring AOP 机制
@RestControllerAdvice   //只对Controller代码层级有效
public class SysResultException {

    //当程序发生异常时，如果没有try-catch则直接向上抛出异常
    //该注解只拦截运行时异常
    @ExceptionHandler({RuntimeException.class})
    public Object exception(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        String method = request.getMethod();
        String callback = request.getParameter("callback");
        if (StringUtils.hasLength(callback)) {
            return new JSONPObject(callback, QmResult.fail());
        }
        return QmResult.fail();
    }

}
